import 'package:flutter/material.dart';
import 'package:manual/components/tab_item.dart';
import 'package:manual/pages/cart_page.dart';
import 'package:manual/pages/home_page.dart';
import 'package:manual/pages/mine_page.dart';

class CustomTabBar extends StatefulWidget {
  const CustomTabBar({super.key});

  @override
  CustomTabBarState createState() => CustomTabBarState();
}

class CustomTabBarState extends State<CustomTabBar> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int currentIndex = 0;

  final List<Map<String, String>> tabItems = [
    {
      "defaultIcon": "lib/assets/images/tabbar/tabbar_home.png",
      "selectedIcon": "lib/assets/images/tabbar/tabbar_home_fill.png",
      "label": "Home",
    },
    {
      "defaultIcon": "lib/assets/images/tabbar/tabbar_interview.png",
      "selectedIcon": "lib/assets/images/tabbar/tabbar_interview_fill.png",
      "label": "Interview",
    },
    {
      "defaultIcon": "lib/assets/images/tabbar/tabbar_mine.png",
      "selectedIcon": "lib/assets/images/tabbar/tabbar_mine_fill.png",
      "label": "Mine",
    },
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: tabItems.length, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  void onTabTapped(int index) {
    setState(() {
      currentIndex = index;
      if (_tabController.index != index) {
        _tabController.animateTo(index);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: null,
      body: TabBarView(
        controller: _tabController,
        physics: const NeverScrollableScrollPhysics(), 
        children: [
          const HomePage(),
          CartPage(),
          const MinePage(),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentIndex,
        onTap: onTabTapped,
        type: BottomNavigationBarType.fixed,
        /* 
        BottomNavigationBarType.fixed：固定布局，图标和文字始终显示（适用于少于 4 个选项）。
        BottomNavigationBarType.shifting：动态布局，未选中的图标文字隐藏，选中的高亮（适用于多于 4 个选项）。
         */
        items: tabItems.map((item) {
          final index = tabItems.indexOf(item);
          return BottomNavigationBarItem(
            icon: Padding(
              // padding: const EdgeInsets.only(top: 0.0),
              padding: EdgeInsets.zero, // 清除任何默认的内边距
              child: TabBarItem(
                defaultIconPath: item["defaultIcon"]!,
                selectedIconPath: item["selectedIcon"]!,
                label: item["label"]!,
                isSelected: currentIndex == index,
              ),
            ),
            label: '',
          );
        }).toList(),
      ),
    );
  }
}
